package com.ajc.seata.config;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;

/**
 * @Author: AnJunchao
 * @Description:
 * @Date: Create in 2019-10-11 15:01:34
 * @Modified By:
 */
@Configuration
@EnableConfigurationProperties
@EnableAutoConfiguration
@ComponentScan
@EnableTransactionManagement
public class DataSourceConfig {
    /**
     * transaction manager
     *
     * @return
     */
    @Bean(name="userTransaction")
    public UserTransaction userTransaction() {
        UserTransactionImp userTransactionImp = new UserTransactionImp();
        //配置事务超时时间
        try {
            userTransactionImp.setTransactionTimeout(500);
        } catch (SystemException e) {
            e.printStackTrace();
        }
        return userTransactionImp;
    }

    /**
     * jta transactionManager  spring对jta的支持
     * @return AtomikosJtaPlatform.transactionManager = userTransactionManager;
     */
    @Bean(destroyMethod = "close", initMethod = "init",name = "xaTransactionManager")
    public TransactionManager userTransactionManager() {
        UserTransactionManager userTransactionManager = new UserTransactionManager();
        userTransactionManager.setForceShutdown(false);//设置为true 网络出现问题时 强制断掉
        AtomikosJtaPlatform.transactionManager = userTransactionManager;
        return userTransactionManager;
    }

    @Bean(name = "transactionManager")
    @DependsOn({"userTransaction", "xaTransactionManager"})
    public PlatformTransactionManager transactionManager() throws Throwable {
        UserTransaction userTransaction = userTransaction();
        AtomikosJtaPlatform.transaction = userTransaction;
        TransactionManager atomikosTransactionManager = userTransactionManager();
        return new JtaTransactionManager(userTransaction, atomikosTransactionManager);
    }
}
